#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@fileName     : log.py
@description  : 
@time         : 2021年10月20日 15:58
@author       : WeiTingjun
@versions     : 1.0
'''
import time
import os
import logging
from logging.handlers import TimedRotatingFileHandler

from epwechat.config import Config

LOG_ROOT_DIRECTORY = Config().get_section('FilePath', 'log').get('log')


class Log(logging.Logger):
    """
    日志分片类
    stream ：控制是否打印日志到控制台
    files：控制是否写入日志文件
    level：日志登记
    prefix_name：日志前缀名称，格式为 prefix_name + '_' + 20180703 + '.log'，如：log_20180703.log
    """

    def __init__(self, prefix_name='log', level='DEBUG', stream=False, files=True):
        self.name = prefix_name
        self.level = level
        logging.Logger.__init__(self, self.name, level=self.level)
        if files:
            self.__file_handler(self.level)
        if stream:
            self.__stream_handler(self.level)

    def __file_handler(self, level=None):  # 存入日志文件
        log_name = os.path.join(LOG_ROOT_DIRECTORY, self.name + '_' + time.strftime('%Y%m%d') + '.log')
        handler = TimedRotatingFileHandler(log_name,
                                           when='D',
                                           interval=1,
                                           backupCount=0)
        handler.setLevel(level)
        formatter = logging.Formatter('%(asctime)s  %(levelname)s  %(pathname)s [line:%(lineno)d]\n%(message)s')
        handler.setFormatter(formatter)
        self.addHandler(handler)

    def __stream_handler(self, level=None):  # 控制台输出
        handler = logging.StreamHandler()
        formatter = logging.Formatter('%(asctime)s  %(levelname)s  %(pathname)s [line:%(lineno)d]%(message)s')
        handler.setFormatter(formatter)
        handler.setLevel(level)
        self.addHandler(handler)


logger = Log()  # 防止unittests运行 打印重复日志
